<template>
  <div class="articlesList-container">
    <el-table :data="list" stripe>
      <el-table-column
        prop="articleName"
        label="文章名"
        width="180"
      ></el-table-column>
      <el-table-column label="封面" width="180">
        <template slot-scope="scope">
          <el-image
            v-if="imgShow"
            :preview-src-list="imageList"
            style="width: 140px; height: 100px"
            :src="scope.row.img"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类别" width="180">
        <template slot-scope="scope">
          <el-tag size="medium">
            {{ scope.row.type }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          {{ scope.row.time | toDate }}
        </template>
      </el-table-column>
      <el-table-column label="修改时间">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          {{ scope.row.modified | toDate }}
        </template>
      </el-table-column>
      <el-table-column prop="pageView" label="阅读量" width="150">
        <template slot-scope="scope">
          <el-tag size="medium">
            {{ scope.row.pageView }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="pageView" label="评论量" width="150">
        <template slot-scope="scope">
          <el-tag size="medium">
            {{ scope.row.comments_num || 0 }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button
            type="success"
            size="mini"
            @click="handlecomment(scope.row.id)"
          >
            评论
          </el-button>
          <el-button
            size="mini"
            type="primary"
            @click="handleSee(scope.row.id)"
          >
            预览
          </el-button>
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm
            title="这是确定删除吗？"
            @onConfirm="handleDelete(scope.row.id)"
          >
            <el-button slot="reference" size="mini" type="danger">
              删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="预览效果" :visible.sync="dialogTableVisible1">
      <div style="min-height: 60vh">
        <div class="news-content">
          <div class="news-content" v-html="content"></div>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="评论" :visible.sync="dialogTableVisible2">
      <div style="min-height: 60vh">
        <div class="news-content">
          <el-table :data="commentlist" stripe>
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column
              label="评论ID"
              width="80"
              prop="id"
            ></el-table-column>
            <el-table-column
              label="用户名"
              prop="author"
              width="100"
            ></el-table-column>
            <el-table-column label="评论内容" width="300">
              <template slot-scope="scope">
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="scope.row.content"
                  placement="top-start"
                >
                  <el-tag size="medium">
                    {{ scope.row.content }}
                  </el-tag>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="时间" width="200">
              <template slot-scope="scope">
                <i class="el-icon-time"></i>
                {{ scope.row.created | toDate }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template slot-scope="scope">
                <el-popconfirm
                  title="这是确定删除吗？"
                  @onConfirm="handleDelete(scope.row.id)"
                >
                  <el-button slot="reference" size="mini" type="danger">
                    删除
                  </el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :background="background"
            :current-page="queryComment.pageNo"
            :layout="layout"
            :page-size="queryComment.pageSize"
            :total="total1"
            @current-change="handleCurrentChange1"
            @size-change="handleSizeChange1"
          ></el-pagination>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="编辑" :visible.sync="dialogTableVisible3">
      <div style="min-height: 60vh">
        <div class="news-content">
          <div class="left">
            <el-form
              ref="elForm"
              :model="articles"
              :rules="rules"
              size="medium"
              label-width="100px"
            >
              <el-form-item label="标题" prop="title">
                <el-input v-model="articles.title" maxlength="20"></el-input>
              </el-form-item>
              <el-form-item label="封面" prop="img">
                <el-upload
                  class="avatar-uploader"
                  action=""
                  :show-file-list="false"
                  :auto-upload="false"
                  :on-change="handleAvatarChange"
                >
                  <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="文章分类" prop="category">
                <el-select v-model="articles.category" placeholder="请选择">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="内容" prop="content">
                <vab-quill
                  v-model="articles.content"
                  :min-height="350"
                ></vab-quill>
              </el-form-item>
              <el-form-item size="large">
                <el-button type="primary" @click="handlesee">
                  预览效果
                </el-button>
                <el-button type="primary" @click="submitForm(articles.id)">
                  提交
                </el-button>
                <el-popconfirm
                  style="margin-left: 10px"
                  confirm-button-text="确定"
                  cancel-button-text="不用了"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定要重置内容吗？"
                  @onConfirm="resetForm"
                >
                  <el-button slot="reference">重置</el-button>
                </el-popconfirm>
              </el-form-item>
            </el-form>
          </div>
          <el-dialog title="预览效果" :visible.sync="dialogTableVisible">
            <div style="min-height: 60vh">
              <div class="news-content" v-html="articles.content"></div>
            </div>
          </el-dialog>
        </div>
      </div>
    </el-dialog>
    <el-pagination
      :background="background"
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    ></el-pagination>
  </div>
</template>

<script>
  import { mapGetters } from "vuex";
  import {
    getList,
    doDelete,
    seearticle,
    getcommentById,
    editArticle,
  } from "@/api/article";
  import vabQuill from "@/plugins/vabQuill";
  export default {
    name: "ArticlesList",
    components: {
      vabQuill,
    },
    filters: {
      toDate(nS) {
        if (nS == null) {
          return "无";
        } else {
          let date = new Date(parseInt(nS));
          let Y = date.getFullYear() + "年";
          let M =
            (date.getMonth() + 1 < 10
              ? "0" + (date.getMonth() + 1)
              : date.getMonth() + 1) + "月";
          let D = date.getDate() + "日";
          return Y + M + D;
        }
      },
    },

    data() {
      return {
        commentlist: [],
        dialogTableVisible: false,
        dialogTableVisible1: false,
        dialogTableVisible2: false,
        dialogTableVisible3: false,
        content: "",
        imgShow: true,
        queryForm: {
          pageNo: 1,
          pageSize: 10,
        },
        queryComment: {
          pageNo: 1,
          pageSize: 10,
        },
        total: 0,
        total1: 0,
        list: [],
        imageList: [],
        background: true,
        layout: "total, prev, pager, next, jumper",
        articles: {
          id: 0,
          content: "",
          title: "",
          img: null,
          category: "",
        },
        imageUrl: "",
        options: [
          {
            value: "程序人生",
            label: "程序人生",
          },
          {
            value: "游戏开发",
            label: "游戏开发",
          },
          {
            value: "移动开发",
            label: "移动开发",
          },
          {
            value: "研发管理",
            label: "研发管理",
          },
          {
            value: "计算机基础",
            label: "计算机基础",
          },
          {
            value: "运维安全",
            label: "运维安全",
          },
          {
            value: "前端架构",
            label: "前端架构",
          },
          {
            value: "后端架构",
            label: "后端架构",
          },
          {
            value: "算法研发",
            label: "算法研发",
          },
          {
            value: "Python开发",
            label: "Python开发",
          },
          {
            value: "软件测试",
            label: "软件测试",
          },
          {
            value: "Java开发",
            label: "Java开发",
          },
          {
            value: "产品设计",
            label: "产品设计",
          },
          {
            value: "原型设计",
            label: "原型设计",
          },
          {
            value: "音视频开发",
            label: "音视频开发",
          },
          {
            value: "人工智能",
            label: "人工智能",
          },
          {
            value: "软件工程",
            label: "软件工程",
          },
          {
            value: "大数据开发",
            label: "大数据开发",
          },
          {
            value: "操作系统",
            label: "操作系统",
          },
          {
            value: "数据分析",
            label: "数据分析",
          },
        ],
        value: "",
        rules: {
          title: [
            {
              required: true,
              message: "请输入标题",
              trigger: "blur",
            },
          ],
          category: {
            required: true,
            message: "请选择文章分类",
            trigger: "blur",
          },
          content: [
            {
              required: true,
              message: "请输入编辑器",
              trigger: "blur",
            },
          ],
        },
      };
    },
    computed: {
      ...mapGetters({
        username: "user/username",
        permissions: "user/permissions",
      }),
    },
    created() {},
    mounted() {
      console.log(this.permissions);
      this.getData();
    },
    methods: {
      async getData() {
        this.$baseColorfullLoading(1, "正在加载", (loading) => {
          getList(this.queryForm).then((res) => {
            console.log(res);
            this.list = res.data;
            this.total = res.totalCount;
            const imageList = [];
            res.data.forEach((item, index) => {
              imageList.push(item.img);
            });
            this.imageList = imageList;
            this.total = res.num;
            loading.close();
          });
        });
      },
      handleCurrentChange(val) {
        this.queryForm.pageNo = val;
        this.$baseColorfullLoading(1, "正在加载", (loading) => {
          this.getData();
        });
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val;
        this.$baseColorfullLoading(1, "正在加载", (loading) => {
          this.getData();
        });
      },
      handleDelete(id) {
        console.log(id);
        let form = new FormData();
        form.append("id", id);
        this.$baseColorfullLoading(1, "正在加载", (loading) => {
          doDelete(form).then((res) => {
            console.log(res);
            this.getData();
            loading.close();
          });
        });
      },
      handleEdit(row) {
        console.log(row);
        seearticle({ id: row.id }).then((res) => {
          console.log(res.data);
          this.articles.id = res.data.id;
          this.articles.content = res.data.content;
          this.articles.category = res.data.categories;
          this.articles.title = res.data.title;
          this.imageUrl = res.data.thumbnail;
        });
        this.dialogTableVisible3 = true;
      },
      handleSee(id) {
        seearticle({ id }).then((res) => {
          console.log(res.data);
          this.content = res.data.content;
          this.dialogTableVisible1 = true;
        });
      },
      handlecomment(id) {
        getcommentById({ id, pageNo: 1, pageSize: 10 }).then((res) => {
          console.log(res);
          this.commentlist = [];
          res.data.forEach((item) => {
            this.commentlist.push(item);
          });
        });
        this.dialogTableVisible2 = true;
      },
      submitForm(id) {
        this.$refs["elForm"].validate((valid) => {
          if (!valid) return;
          //TODO 提交表单
          this.$baseColorfullLoading(1, "正在提交", (loading) => {
            var formData = new FormData();
            if (this.articles.img != null) {
              let file = this.dataURLtoFile(
                this.articles.img,
                this.articles.title
              );
              formData.append("file", file);
            }
            formData.append("id", id);
            formData.append("content", this.articles.content);
            formData.append("title", this.articles.title);
            formData.append("categories", this.articles.category);
            editArticle(formData).then((res) => {
              console.log(res);
              if (res.code == 200) {
                this.getData();
                loading.close();
                this.$message({
                  message: "提交成功",
                  type: "success",
                });
                this.dialogTableVisible3 = false;
              }
            });
          });
        });
      },
      resetForm() {
        this.$refs["elForm"].resetFields();
        this.imageUrl = null;
        this.$message("已重置内容");
      },
      handleAvatarChange(file) {
        this.blobToBase64(file.raw).then((res) => {
          // 转化后的base64
          this.articles.img = res;
          this.imageUrl = URL.createObjectURL(file.raw);
        });
      },
      blobToBase64(blob) {
        return new Promise((resolve, reject) => {
          const fileReader = new FileReader();
          fileReader.onload = (e) => {
            resolve(e.target.result);
          };
          // readAsDataURL
          fileReader.readAsDataURL(blob);
          fileReader.onerror = () => {
            reject(new Error("blobToBase64 error"));
          };
        });
      },
      dataURLtoFile(dataurl, filename) {
        //将base64转换为文件
        var arr = dataurl.split(","),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, { type: mime });
      },
      handlesee() {
        this.dialogTableVisible = true;
      },
      handleCurrentChange1(val) {
        this.queryComment.pageNo = val;
        this.$baseColorfullLoading(1, "正在加载", (loading) => {
          getcommentById({
            id,
            pageNo: this.queryComment.pageNo,
            pageSize: this.queryComment.pageSize,
          }).then((res) => {
            console.log(res);
            this.commentlist = [];
            res.data.forEach((item) => {
              this.commentlist.push(item);
            });
          });
        });
      },
      handleSizeChange1(val) {
        this.queryComment.pageSize = val;
        this.$baseColorfullLoading(1, "正在加载", (loading) => {
          getcommentById({
            id,
            pageNo: this.queryComment.pageNo,
            pageSize: this.queryComment.pageSize,
          }).then((res) => {
            console.log(res);
            this.commentlist = [];
            res.data.forEach((item) => {
              this.commentlist.push(item);
            });
          });
        });
      },
    },
  };
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  .avatar {
    width: 200x;
    height: 150px;
    display: block;
  }
</style>
